<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\Order as OrderModel;
use app\api\service\User as UserService;
use app\common\model\OrderSub as OrderSubModel;
use app\common\service\bangdou\Common as CommonService;
use app\api\model\Setting as SettingModel;
use app\api\service\UserBd as UserBdService;
use app\common\service\bangdou\BdPay as BdPayService;
use app\common\service\wxpush\WXBizMsgCrypt;
use app\store\model\Express as ExpressModel;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use cores\exception\BaseException;
use think\response\Json;
use app\api\model\OrderGoods as OrderGoodsModel;
use app\common\model\OrderAddress as OrderAddressModel;

/**
 * 我的订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /**
     * 获取当前用户待处理的订单数量
     * @return Json
     * @throws BaseException
     */
    public function todoCounts(): Json
    {
        $model  = new OrderModel;
        $counts = $model->getTodoCounts();
        return $this->renderSuccess(compact('counts'));
    }

    /**
     * 我的订单列表
     * @param string $dataType 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
     * @return Json
     * @throws \think\db\exception\DbException
     * @throws BaseException
     */
    public function list(string $dataType): Json
    {
        $model = new OrderModel;
        $list  = $model->getList($dataType);
        foreach ($list as $key=>$item){
            if($item['goods']){
                foreach ($item['goods'] as $good_info){
                    $list[$key]['good_type'] = $good_info['good_type'];
                }
            }
        }
        if ($dataType == 'all' || $dataType == 'comment') {
            $list = $model->getAllList($list->toArray());
            return $this->renderSuccess(array('list' => $list));
        }
        // var_dump($list);exit;
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 订单详情信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function detail(int $orderId): Json
    {
        // 订单详情
        $model = OrderModel::getUserOrderDetail($orderId);
        return $this->renderSuccess([
            'order'   => $model,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
        ]);
    }

    /**
     * 获取物流信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function express(int $orderId): Json
    {
        // 订单信息
        $order = OrderModel::getDetail($orderId);
        if (!$order['express_no']) {
            return $this->renderError('没有物流信息');
        }
        $orderAddress['phone'] = '';
        if(isset($order['order_parent_id']) && $order['order_parent_id']){
            $orderAddress = OrderAddressModel::get(['order_id'=>$order['order_parent_id']]);
        }
        // 获取物流信息
        $model   = ExpressModel::detail($order['express_id']);
        $express = $model->dynamic($model['express_name'], $model['kuaidi100_code'], $order['express_no'],$orderAddress['phone']);
        if ($express === false) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess(compact('express'));
    }

    /**
     * 取消订单
     * @param int $orderId
     * @return Json
     * @throws BaseException
     */
    public function cancel(int $orderId): Json
    {
        $model = OrderModel::getDetail($orderId);
        if ($model->cancel()) {
            return $this->renderSuccess('订单取消成功');
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }

    /**
     * 确认收货
     * @param int $orderId
     * @return Json
     * @throws BaseException
     */
    public function receipt(int $orderId): Json
    {
        $model = OrderModel::getDetail($orderId);
        if ($model->receipt()) {
            return $this->renderSuccess('确认收货成功');
        }
        return $this->renderError($model->getError());
    }

    /**
     * 立即支付
     * @param int $orderId 订单ID
     * @param int $payType 支付方式
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function pay(int $orderId, int $payType = OrderPayTypeEnum::WECHAT): Json
    {
        $post_data = $this->postData();
        // 获取订单详情
        $model = OrderModel::getUserOrderDetail($orderId);
        // 订单支付事件
        if (!$model->onPay($payType)) {
            return $this->renderError($model->getError() ?: '订单支付失败');
        }
        // 更新子订单详情
        if (isset($post_data['dk_money'])) {
            $detail['dk_money'] = $post_data['dk_money'];
        }
        if (isset($post_data['pay_money'])) {
            $detail['pay_money'] = $post_data['pay_money'];
        }
        $detail['bdType']    = isset($post_data['bdType']) ? $post_data['bdType'] : "0";
        $detail['order_id']  = $orderId;
        $detail['pay_price'] = $model['pay_price'];
        //更新商品表
        $update = OrderGoodsModel::updateOrderInfo($detail);
        if (empty($update)) {
            return $this->renderError($model->getError() ?: '支付方式异常');
        }
        $subModel = OrderSubModel::getOrderSubBy($orderId);
        if (empty($subModel) || $subModel['state'] != 10) {
            return $this->renderError($model->getError() ?: '订单子表异常');
        }
        // 构建微信支付请求
        //$payment = $model->onOrderPayment($model, $payType);
        $data['payType']          = $payType;
        $data['pay_money']        = $subModel['pay_money'];
        $data['dk_money']         = $subModel['deduction_value'];
        $data['bdType']           = $subModel['bd_type'];
        $data['store_id']         = $model['store_id'];
        $data['order_no']         = $model['order_no'];
        $data['order_id']         = $model['order_id'];
        $data['good_type']        = $model['good_type'];//是否虚拟商品订单
        $data['recharge_account'] = $model['recharge_account'] ?? '';
        $data['goods_no']         = $model['goods_no'] ?? '';
        //构建邦豆支付微信请求
        $payment = BdPayService::bangddouPay($data, $model['user_id']);//提交支付
        // 支付状态提醒
        return $this->renderSuccess([
            'order_id' => $model['order_id'],   // 订单id
            'pay_type' => $payType,             // 支付方式
            'payment'  => $payment               // 微信支付参数
        ]);
    }

    public function count()
    {
        $data = $this->postData();
        if (empty($data['orderId'])) {
            return $this->renderError('参数错误');
        }
        //获取订单信息
        $model = OrderModel::getUserOrderDetail(intval($data['orderId']));
        if ($model['pay_price'] > 0) {
            // 当前用户信息
            $userInfo           = UserService::getCurrentLoginUser(true);
            $bd_coupon          = UserBdService::getBdCoupon($userInfo['currentOauth']['bd_uid']);
            $bd_coupon['balance'] = $userInfo['balance'];//余额
            $unsupportedBdPrice = '0.00';
            //不能使用三券的订单
            if (isset($model['goods'])) {
                $result             = UserBdService::getUserOrderUnsupportedBd($model['goods']->toarray());
                $unsupportedBdPrice = $result['unsupportedBdPrice'];
            }
            $result = UserBdService::countAmount($model['pay_price'], $data['payType'], $bd_coupon, $unsupportedBdPrice);
        }
        return $this->renderSuccess([
            'pay_money' => isset($result['pay_money']) ? $result['pay_money'] : 0.00,             // 支付金额
            'dk_money'  => isset($result['dk_money']) ? $result['dk_money'] : 0.00              // 三券抵扣金额
        ]);
    }

    /**
     * 确认收货
     * 微信回调确认收货
     * @return Json
     * @throws BaseException
     */
    public function wxReceipt(): Json
    {
        $log_file = runtime_root_path() . 'api/log/wx_Receipt_' . date('y-m-d') . '.log';
        file_put_contents($log_file, print_r($_REQUEST, true) . "\n", FILE_APPEND);

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];

        $token  = 'bq5xbsqLV3D948Sbgq2ii0ll';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }

        /*$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
        $encryptMsg = '';
        $errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
        if ($errCode == 0) {
            print("加密后: " . $encryptMsg . "\n");
        } else {
            print($errCode . "\n");
        }

        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $array_s = $xml_tree->getElementsByTagName('MsgSignature');
        $encrypt = $array_e->item(0)->nodeValue;
        $msg_sign = $array_s->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);

        // 第三方收到公众号平台发送的消息
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            print("解密后: " . $msg . "\n");
        } else {
            print($errCode . "\n");
        }*/

        $model = OrderModel::getDetail($orderId);
        if ($model->receipt()) {
            return $this->renderSuccess('确认收货成功');
        }
        return $this->renderError($model->getError());
    }

}
